import json
import logging
import time

import framework
import pymysql

# logging日志的配置
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
    filename="log.txt",
    filemode="w",
)
routerList = [
    # ("/index.html", indexHeadle),
    # ("/center.html", centerHeadle),
]


def router(url):
    def decorator(func):
        routerList.append((url, func))

        def inner():
            return func()

        return inner

    return decorator


@router("/index.html")
def indexHeadle():
    currentTime = time.time()
    print("当前时间indexHeadle：%s" % currentTime)
    status = "200 ok"
    headers = [("Server", "PWS2.0")]
    with open("template/index.html", "r", encoding="utf-8") as file:
        fileData = file.read()
        print(fileData)
    # responseBoy = fileData.replace("{%content%}", str(currentTime)).encode("utf8")
    # INFO:股票信息获取
    conn = pymysql.connect(
        host="192.168.5.116",
        port=3306,
        user="root",
        password="mysql",
        database="python",
        charset="utf8",
    )
    cursor = conn.cursor()
    sql = "select * from info;"
    cursor.execute(sql)
    result = cursor.fetchall()
    print(result)
    data = ""
    for row in result:
        data += (
            """<tr>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td><input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007"></td>
                </tr>"""
            % row
        )
        responseBoy = fileData.replace("{%content%}", data).encode("utf8")
    conn.close()
    cursor.close()
    return status, headers, responseBoy


@router("/center.html")
def centerHeadle():
    currentTime = time.time()
    print("当前时间centerHeadle：%s" % currentTime)
    status = "200 ok"
    headers = [("Server", "PWS2.0")]
    with open("template/center.html", "r", encoding="utf-8") as file:
        fileData = file.read()
        print(fileData)
    responseBoy = fileData.replace("{%content%}", str(currentTime)).encode("utf8")
    return status, headers, responseBoy


@router("/centerData.html")
def cneterData():
    status = "200 ok"
    headers = [("Server", "PWS2.0")]
    conn = pymysql.connect(
        host="192.168.5.116",
        port=3306,
        user="root",
        password="mysql",
        database="python",
        charset="utf8",
    )
    cursor = conn.cursor()
    sql = "SELECT i.code ,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info FROM info i INNER JOIN focus f ON i.id=f.id;"
    cursor.execute(sql)
    result = cursor.fetchall()
    print("result", result)
    centerDataLiat = list()
    for row in result:
        centerDict = dict()
        centerDict["code"] = row[0]
        centerDict["short"] = row[1]
        centerDict["chg"] = row[2]
        centerDict["turnover"] = row[3]
        centerDict["price"] = str(row[4])
        centerDict["highs"] = str(row[5])
        centerDict["note_info"] = row[6]
        centerDataLiat.append(centerDict)

    print(centerDataLiat)
    jsonStr = json.dumps(centerDataLiat, ensure_ascii=False)
    print(jsonStr)
    conn.close()
    cursor.close()
    return status, headers, jsonStr.encode("utf-8")


def notFound():
    currentTime = time.time()
    print("当前时间notFound：%s" % currentTime)

    status = "200 ok"
    headers = [("Server", "PWS2.0")]
    responseBoy = "<p>404 Not Found~:%s" % currentTime + "</p>"
    return status, headers, responseBoy.encode("utf8")


def handle_request(env):
    print("接收参数：%s" % env)
    print(routerList)
    url = env["reqUrl"]
    for path, fn in routerList:
        if path == url:
            return fn()
        # if url == "/index.html":
        #     return indexHeadle()
        # elif url == "/center.html":
        #     return centerHeadle()
    else:
        logging.error("没有设置相应的路由:" + url)
        return notFound()


""" if __name__ == "__main__":
    cneterData()
 """
